package com.example.service;

import org.springframework.stereotype.Service;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;

import jakarta.annotation.Resource;

/**
 * 以太坊链基础服务
 */
@Service
public class EthService {

    @Resource
    private Web3j web3j;

    @jakarta.annotation.Resource
    private org.web3j.crypto.Credentials signer;

    /**
     * ETH 转账
     * @param to 目标地址
     * @param amount 金额（单位：Wei）
     * @return 交易哈希
     */
    public String transferEth(String to, java.math.BigInteger amount) throws Exception {
        org.web3j.protocol.core.methods.response.EthSendTransaction response =
                web3j.ethSendTransaction(new org.web3j.protocol.core.methods.request.Transaction(
                        signer.getAddress(), null, null, null, to, amount, null)).send();
        if (response.hasError()) {
            throw new RuntimeException("ETH转账失败: " + response.getError().getMessage());
        }
        return response.getTransactionHash();
    }


    /**
     * 查询ETH余额（单位：Wei）
     */
    public java.math.BigInteger getEthBalance(String address) throws Exception {
        return web3j.ethGetBalance(address, org.web3j.protocol.core.DefaultBlockParameterName.LATEST)
                .send().getBalance();
    }

    /**
     * 获取最新区块号
     */
    public long getBlockNumber() throws Exception {
        EthBlockNumber blockNumber = web3j.ethBlockNumber().send();
        return blockNumber.getBlockNumber().longValue();
    }

}
